<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/7/18
 * Time: 17:59
 */
namespace app\pay\controller;

use think\Controller;
use think\Request;

class AlipayController extends  Controller
{

    private $_notifyObj;

    public function index()
    {
        $alipay_config = config('alipay_config');

        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
//        $out_trade_no = $_POST['WIDout_trade_no'];
        $out_trade_no = date('YmdHis') . rand(1000, 9999);
        //订单名称，必填
//        $subject = $_POST['WIDsubject'];
        $subject = 'test商品123';
        //付款金额，必填
//        $total_fee = $_POST['WIDtotal_fee'];
        $total_fee = '0.01';

        //商品描述，可空
//        $body = $_POST['WIDbody'];
        $body = '';
        /************************************************************/
//生成订单，并记录订单详情
        //订单号
        $out_trade_no = date('YmdHis') . rand(1000, 9999);
        //


//构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => $alipay_config['service'],
            "partner" => $alipay_config['partner'],
            "seller_id" => $alipay_config['seller_id'],
            "payment_type" => $alipay_config['payment_type'],
            "notify_url" => $alipay_config['notify_url'],
            "return_url" => $alipay_config['return_url'],

            "anti_phishing_key" => $alipay_config['anti_phishing_key'],
            "exter_invoke_ip" => $alipay_config['exter_invoke_ip'],
            "out_trade_no" => $out_trade_no,
            "subject" => $subject,
            "total_fee" => $total_fee,
            "body" => $body,
            "_input_charset" => trim(strtolower($alipay_config['input_charset']))
            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.kiX33I&treeId=62&articleId=103740&docType=1
            //如"参数名"=>"参数值"

        );
        //建立请求
        $alipaySubmit = new \Alipay\lib\AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
        echo $html_text;
    }

    //同步返回，用于提示页面
    public function  backtome()
    {

        //同步验证，接受到的请求进行验证
        $alipay_config = config('alipay_config');
        $this->_notifyObj = new \Alipay\lib\AlipayNotify($alipay_config);
        $verifyResult = $this->_notifyObj->verifyReturn();
        if ($verifyResult)
        {
            $arr = Request::instance()->param();
            /*
             * array(18) {
                      ["/pay/alipay/backtome"] => string(0) ""
                      ["buyer_email"] => string(17) "1187058988@qq.com"
                      ["buyer_id"] => string(16) "2088902359168081"
                      ["exterface"] => string(25) "create_direct_pay_by_user"
                      ["is_success"] => string(1) "T"
                      ["notify_id"] => string(72)  "RqPnCoPT3K9%2Fvwbh3Ih20lxLHYGJ2kabhYI6wkmP3PgPIs92w%2BD7y12tabE4O3Imwppp"
                      ["notify_time"] => string(19) "2017-07-19 11:13:42"
                      ["notify_type"] => string(17) "trade_status_sync"
                      ["out_trade_no"] => string(18) "201707191112074503"
                      ["payment_type"] => string(1) "1"
                      ["seller_email"] => string(15) "pimc_cn@163.com"
                      ["seller_id"] => string(16) "2088621522746340"
                      ["subject"] => string(13) "test商品123"
                      ["total_fee"] => string(4) "0.01"
                      ["trade_no"] => string(28) "2017071921001004080256229419"
                      ["trade_status"] => string(13) "TRADE_SUCCESS"
                      ["sign"] => string(32) "ac039e28c907446014222faff45a1b50"
                      ["sign_type"] => string(3) "MD5"
                    }
             * */
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
            $out_trade_no   = $arr['out_trade_no'];      //商户订单号
            $trade_no       = $arr['trade_no'];          //支付宝交易号
            $trade_status   = $arr['trade_status'];      //交易状态
            $total_fee      = $arr['total_fee'];         //交易金额
            $notify_id      = $arr['notify_id'];         //通知校验ID。
            $notify_time    = $arr['notify_time'];       //通知的发送时间。
            $buyer_email    = $arr['buyer_email'];       //买家支付宝帐号；

            $parameter = array(
                "out_trade_no"     => $out_trade_no,      //商户订单编号；
                "trade_no"     => $trade_no,          //支付宝交易号；
                "total_fee"      => $total_fee,         //交易金额；
                "trade_status"     => $trade_status,      //交易状态
                "notify_id"      => $notify_id,         //通知校验ID。
                "notify_time"    => $notify_time,       //通知的发送时间。
                "buyer_email"    => $buyer_email,       //买家支付宝帐号
            );

            if($arr['trade_status'] == 'TRADE_FINISHED' || $arr['trade_status'] == 'TRADE_SUCCESS') {
                if(!$this->checkorderstatus($out_trade_no)){
                    $this->orderhandle($parameter);  //进行订单处理，并传送从支付宝返回的参数；
                }
                return ['code'=>0,'支付成功'];//跳转到配置项中配置的支付成功页面；
            }else {
//                echo "trade_status=".$_GET['trade_status'];
                return  ['code'=>1,'msg'=>$arr['trade_status']];
            }
        } else
        {
            return ['code' => 1, 'msg' => '支付异常'];
        }

    }

    //异步提醒，用于更新订单状态
    public function  notify()
    {
        //接受到的请求进行验证
        $alipay_config = config('alipay_config');
        $this->_notifyObj = new \Alipay\lib\AlipayNotify($alipay_config);
        $verifyResult = $this->_notifyObj->verifyNotify();
        if ($verifyResult)
        {
            //验证成功
            $arr = Request::instance()->param();
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            $out_trade_no   = $arr['out_trade_no'];      //商户订单号
            $trade_no       = $arr['trade_no'];          //支付宝交易号
            $trade_status   = $arr['trade_status'];      //交易状态
            $total_fee      = $arr['total_fee'];         //交易金额
            $notify_id      = $arr['notify_id'];         //通知校验ID。
            $notify_time    = $arr['notify_time'];       //通知的发送时间。格式为yyyy-MM-dd HH:mm:ss。
            $buyer_email    = $arr['buyer_email'];       //买家支付宝帐号；
            $parameter = array(
                "out_trade_no"     => $out_trade_no, //商户订单编号；
                "trade_no"     => $trade_no,     //支付宝交易号；
                "total_fee"     => $total_fee,    //交易金额；
                "trade_status"     => $trade_status, //交易状态
                "notify_id"     => $notify_id,    //通知校验ID。
                "notify_time"   => $notify_time,  //通知的发送时间。
                "buyer_email"   => $buyer_email,  //买家支付宝帐号；
            );
            if($arr['trade_status'] == 'TRADE_FINISHED' || $arr['trade_status'] == 'TRADE_SUCCESS')
            {
                if (!$this->checkorderstatus($out_trade_no))
                {
                    $this->orderhandle($parameter);  //进行订单处理，并传送从支付宝返回的参数；
                }

                echo "success";        //请不要修改或删除
            }
        } else
        {

            //验证失败
            echo "fail";
        }
    }

    //在线交易订单支付处理函数
//函数功能：根据支付接口传回的数据判断该订单是否已经支付成功；
//返回值：如果订单已经成功支付，返回true，否则返回false；
    function checkorderstatus($orderid)
    {

        $ordstatus = Db::table('orders')->where('order_id',$orderid)->value('status');
        if ($ordstatus == 1)
        {
            return true;
        } else
        {
            return false;
        }
    }

//处理订单函数
//更新订单状态，写入订单支付后返回的数据
    function orderhandle($parameter)
    {
        $ordid = $parameter['out_trade_no'];
        $data['payment_trade_no'] = $parameter['trade_no'];
        $data['payment_trade_status'] = $parameter['trade_status'];
        $data['payment_notify_id'] = $parameter['notify_id'];
        $data['payment_notify_time'] = $parameter['notify_time'];
        $data['payment_buyer_email'] = $parameter[''];
        $data['ordstatus'] = 1;
        $Ord = M('Orderlist');
        $Ord->where('ordid=' . $ordid)->save($data);
    }

//获取一个随机且唯一的订单号；
    function getordcode()
    {
        $Ord = M('Orderlist');
        $numbers = range(10, 99);
        shuffle($numbers);
        $code = array_slice($numbers, 0, 4);
        $ordcode = $code[0] . $code[1] . $code[2] . $code[3];
        $oldcode = $Ord->where("ordcode='" . $ordcode . "'")->getField('ordcode');
        if ($oldcode)
        {
            getordcode();
        } else
        {
            return $ordcode;
        }
    }
}